package com.devgroupvn.dota.hero;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;

import com.devgroupvn.dota.Application;
import com.devgroupvn.dota.data.GetHero;
import com.devgroupvn.dota.data.Hero;

public class PageHero extends LinearLayout
{
	GridView mGridView;
	Context mContext;
	Hero mEntry;
	private List<Hero> listHero = new ArrayList<Hero>();
	GetHero mGetHero;
	AdapterHerro adapter;

	public PageHero(Context context)
	{
		super(context);
		mContext = context;
		init();
		action();
		mGetHero = new GetHero();
		new AsyncGetListHero().execute();
		adapter = new AdapterHerro(listHero, mContext);
		mGridView.setAdapter(adapter);

	}

	// android:numColumns="auto_fit"
	// android:gravity="center"
	// android:columnWidth="100dp"
	// android:stretchMode="columnWidth"
	private void init()
	{
		mGridView = new GridView(mContext);
		LayoutParams params = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);

		addView(mGridView, params);
		mGridView.setNumColumns(3);
		mGridView.setGravity(Gravity.CENTER);

	}

	private void action()
	{
		mGridView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3)
			{
				Intent intent = new Intent(mContext, HeroDetail.class);
				Application.getInstance().putData("entryhero", listHero.get(position));
				mContext.startActivity(intent);
			}
		});
	}

	private class AsyncGetListHero extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected Void doInBackground(Void... params)
		{
			listHero = mGetHero.getListHeroes();
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			// adapter.notifyDataSetChanged();
			if (listHero != null)
			{
				adapter = new AdapterHerro(listHero, mContext);
				mGridView.setAdapter(adapter);
			}
			else
			{
				new AsyncGetListHero().execute();
			}
		}

	}

}
